package com.totoro.tyrank.listener;

import com.totoro.tyrank.constants.InvRankTypeConst;
import com.totoro.tyrank.constants.NBTKeyConst;
import com.totoro.tyrank.inventory.*;
import com.totoro.tyrank.utils.NBTUtil;
import com.totoro.tyrank.utils.StrUtil;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.inventory.ClickType;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.inventory.ItemStack;

public class AttributeReceiveInventoryListener implements Listener {

    @EventHandler
    public void OnFire(InventoryClickEvent e) {
        Player player = (Player) e.getView().getPlayer();
        if (!AttributeReceiveInventory.currentOpenAttribute.containsKey(player.getUniqueId())) {
            return;
        }
        String attributeInvTitle = AttributeReceiveInventory.currentOpenAttribute.get(player.getUniqueId());
        if (e.getView().getTitle().equals(attributeInvTitle)) {
            e.setCancelled(true);
            // 获取点击物品
            ItemStack currentItem = e.getCurrentItem();
            if(null == currentItem || currentItem.getType() == Material.AIR || currentItem.getType() == Material.STAINED_GLASS_PANE) {
                return;
            }
            // 获取NBT上之前的RankType类型
            // 获取NBT上的rankId
            String rankId = "";
            String fromInvRankType = NBTUtil.getNBT(currentItem, NBTKeyConst.FROM_INV_RANK_TYPE);
            if(!StrUtil.isNotBlank(fromInvRankType)) {
                fromInvRankType = InvRankTypeConst.ALL_RANK_INV;
            }
            rankId = NBTUtil.getNBT(currentItem, NBTKeyConst.RANK_ID);
            // 获取点击类型
            ClickType clickType = e.getClick();

            // 如果点击的是返回
            if(e.getRawSlot() == 49) {
                AttributeReceiveInventory.currentOpenAttribute.remove(player.getUniqueId());
                AttributeReceiveInventory.currentPage.put(player.getUniqueId(), 1);
                RankContentInventory.openMainInv(player, rankId, fromInvRankType);
            }

            // 如果点击的是上一页，判断左键还是右键
            if(e.getRawSlot() == 45) {
                if(clickType == ClickType.LEFT) {
                    AttributeReceiveInventory.preCurrentPage(player, rankId, fromInvRankType);
                } else if (clickType == ClickType.RIGHT) {
                    AttributeReceiveInventory.firstCurrentPage(player, rankId, fromInvRankType);
                }
                return;
            }
            // 如果点击的是下一页，判断左键还是右键
            if(e.getRawSlot() == 53) {
                if(clickType == ClickType.LEFT) {
                    AttributeReceiveInventory.nextCurrentPage(player, rankId, fromInvRankType);
                } else if (clickType == ClickType.RIGHT) {
                    AttributeReceiveInventory.lastCurrentPage(player, rankId, fromInvRankType);
                }
                return;
            }
        }
    }
}
